package org.mspring.platform.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author gaoyb(www.mspring.org)
 * @since Mar 5, 2011
 */
public class CookieUtils {

    private static final Logger logger = LoggerFactory.getLogger(CookieUtils.class);

    public static void printCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return;
        }
        for (Cookie cookie : cookies) {
            logger.debug("Cookie[name=" + cookie.getName() + ", value=" + cookie.getValue() + "]");
        }
    }

    public static void setCookie(HttpServletResponse response, String name, String value) {
        setCookie(response, name, value, 0);
    }

    public static void setCookie(HttpServletResponse response, String name, String value, int iExpireDays) {
        try {
            value = org.apache.commons.lang3.StringUtils.isBlank(value) ? "" : value;
            Cookie cookie = new Cookie(name, Base64.encodeBase64String(value.getBytes()));
            if (iExpireDays != 0) {
                cookie.setMaxAge(iExpireDays * 24 * 60 * 60 * 1000);
            }
            cookie.setPath("/");
            response.addCookie(cookie);
            logger.debug("set cookie [" + name + "=" + value + "]");
        } catch (Exception e) {
            logger.warn(String.format("set cookie failure. name = %s, value = %s , iExpireDays = %s", name, value, iExpireDays));
        }
    }

    public static String getCookie(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return "";
        }
        for (Cookie cookie : cookies) {
            if (name.equals(cookie.getName())) {
                try {
                    String value = cookie.getValue();
                    return new String(Base64.decodeBase64(value));
                } catch (Exception e) {
                    logger.warn("get cookie failure. name = " + name, e);
                }
            }
        }
        return "";
    }
}
